#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main()
{
    // 1. 创建并截断文件（确保为空）
    int fd = open("test2.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
    if (fd == -1)
    {
        perror("open");
        exit(EXIT_FAILURE);
    }

    // 2. 设置非阻塞模式并验证
    int flags = fcntl(fd, F_GETFL);
    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
    {
        perror("F_SETFL");
        exit(EXIT_FAILURE);
    }
    if (fcntl(fd, F_GETFL) & O_NONBLOCK)
    {
        printf("Non-blocking mode enabled\n");
    }
    else
    {
        printf("Failed to set non-blocking mode\n");
        exit(EXIT_FAILURE);
    }

    // 3. 验证空文件读取行为
    char buf[20];
    ssize_t n = read(fd, buf, sizeof(buf));
    if (n == 0)
    {
        printf("Read EOF (expected for empty regular file)\n");
    }
    else if (n == -1)
    {
        printf("Unexpected error: %s\n", strerror(errno));
    }
    else
    {
        printf("Unexpected read %zd bytes\n", n);
    }

    // 4. 写入数据后验证读取
    const char *data = "NONBLOCK_TEST";
    if (write(fd, data, strlen(data)) == -1)
    {
        perror("write");
        exit(EXIT_FAILURE);
    }
    lseek(fd, 0, SEEK_SET); // 重置偏移量

    memset(buf, 0, sizeof(buf));
    n = read(fd, buf, sizeof(buf));
    if (n > 0)
    {
        printf("Read after write: '%.*s'\n", (int)n, buf);
    }
    else
    {
        printf("Read failed after write\n");
    }

    close(fd);
    return 0;
}